#! /usr/bin/python
import optparse
import string
import random
import socket
import time
import sys

usage = """
%prog [options]"
Example
python tcp_echo_client.py  --address=127.0.0.1 --port=7 --text="Hello World" 
"""
__version__ = "0.0.0.0"

parser = optparse.OptionParser (usage=usage, version=__version__)

parser.add_option(
        "--address", 
        dest="address",
        default="127.0.0.1",
        help="Server IP address",
        metavar="ADDRESS")

parser.add_option(
        "--port", 
        dest="port",
        type="int",
        default=7,
        help="Server port",
        metavar="PORT")

parser.add_option(
        "--text", 
        dest="text",
        type="string",
        default="Hello World",
        help="Text to send",
        metavar="TEXT")

parser.add_option(
        "--generate", 
        dest="generate",
        action="store_true",
        default=False,
        help="Generate random text to send",
        metavar="GENERATE")

parser.add_option(
        "--generated-length", 
        dest="length",
        type="int",
        default=8192,
        help="if --generate is specified the generated text length",
        metavar="LENGTH")

(options, args) = parser.parse_args()

address = options.address
port = options.port
text = options.text
generate = options.generate
length = options.length
if generate:
    l = []
    for i in xrange(length): 
        l.append(random.choice("%s%s" % (string.uppercase, string.lowercase)))
    text = "".join(l)
    

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((address, port))
s.sendall(text)
sent_len = len(text)
l = []
while(sent_len != 0):
    reply = s.recv(sent_len)
    l.append(reply)
    sent_len -= len(reply)

reply = "".join(l)
#time.sleep(20.0)
#s.shutdown(socket.SHUT_RDWR)
s.close()
if reply == text:
    print "OK"
else:
    print "FAILED"
